package org.uam.common;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * 通用工具
 * 包含功能：批量删除组装id、获得超类通用类型
 * 
 * @author  Leo
 * @version  [版本号, 2012-11-3]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class GenericUtils
{
    private static final Log log = LogFactory.getLog(GenericUtils.class);
    
    /**
     * 获得超类通用类型
     * <功能详细描述>
     * @param clazz 类
     * @return 类
     * @see [类、类#方法、类#成员]
     */
    public static Class getSuperClassGenricType(Class clazz)
    {
        return getSuperClassGenricType(clazz, 0);
    }

    public static Class getSuperClassGenricType(Class clazz, int index)
    {
        // 返回表示此 Class 所表示的实体（类、接口、基本类型或 void）的直接超类的 Type
        Type genType = clazz.getGenericSuperclass();

        // 判断类型是否匹配
        if (!(genType instanceof ParameterizedType))
        {
            log.warn(clazz.getSimpleName()
                    + "'s superclass not ParameterizedType");

            return Object.class;
        }

        // 返回表示此类型实际类型参数的 Type 对象的数组
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0)
        {
            log.warn("Index: " + index + ", Size of " + clazz.getSimpleName()
                    + "'s Parameterized Type: " + params.length);

            return Object.class;
        }
        if (!(params[index] instanceof Class))
        {
            log
                    .warn(clazz.getSimpleName()
                            + " not set the actual class on superclass generic parameter");

            return Object.class;
        }
        return (Class) params[index];
    }

    /**
     * 批量删除组装id
     * 
     * @param ids
     *            id数组
     * @return
     */
    public static String createBlock(Object[] ids)
    {
        if (ids == null || ids.length == 0)
        {
            return "('')";
        }

        String[] str = ids[0].toString().split(",");

        String blockStr = "";

        for (int i = 0; i < str.length - 1; i++)
        {
            blockStr += "'" + str[i] + "',";
        }

        blockStr += "'" + str[str.length - 1] + "'";

        return blockStr;
    }

    /**
     * 组装字符串
     * 
     * @param ids
     *            ids
     * @return
     */
    public static String createBlock(String ids)
    {
        if (null == ids)
        {
            return "";
        }
        String[] str = ids.split(",");

        String blockStr = "";

        for (int i = 0; i < str.length - 1; i++)
        {
            blockStr += "'" + str[i] + "',";
        }

        blockStr += "'" + str[str.length - 1] + "'";

        return blockStr;
    }

}
